package com.example.tabbar.activity

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Rect
import android.os.BatteryManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.tabbar.R
import com.example.tabbar.databinding.ActivityTabarBinding
import com.example.tabbar.fragment.MaintenanceFragment
import com.example.tabbar.fragment.MeaFragment
import com.example.tabbar.fragment.ModeFragment
import com.example.tabbar.fragment.SearchFragment
import com.example.tabbar.fragment.SetFragment
import com.example.tabbar.utils.StatusBarManager
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.internal.ViewUtils.hideKeyboard
import com.junray.usermangement.room.entity.Permission
import com.junray.usermangement.room.entity.Role
import com.junray.usermangement.room.entity.Rule
import com.junray.usermangement.room.entity.User
import com.junray.usermangement.utils.LiveDataUtils.observeOnce
import com.junray.usermangement.utils.SessionManager
import com.junray.usermangement.utils.SessionManager.Companion.instance
import com.junray.usermangement.viewModel.UserViewModel
import com.sdkapi.api.SdkApi

class TabarActivity : AppCompatActivity() {
    private var bottomTab : BottomNavigationView? = null
    private lateinit var binding : ActivityTabarBinding
    private var statusBarManager: StatusBarManager? = null
    private var batteryReceiver: BroadcastReceiver? = null
    private var sessionManager : SessionManager? = null
    private var userViewmodel: UserViewModel? = null


    // 用来跟踪维护tab的显示状态
    private var isMaintenanceTabVisible = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        //3588屏幕api隐藏导航栏
//        SdkApi.getInstance().SystemCtrl().statusBarDisplay = !SdkApi.getInstance().SystemCtrl().statusBarDisplay

        binding = ActivityTabarBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 初始化状态栏管理器
        val customNavBarBinding = binding.tabbar
        statusBarManager = StatusBarManager(customNavBarBinding)
        statusBarManager?.startUpdates()

        hideSystemBars()

        setupBottomNavigation()

        userViewmodel = ViewModelProvider(this)[(UserViewModel::class.java)]
        //初始化全局会话窗口
        sessionManager = instance

        //模拟登录***
        observeOnce(userViewmodel!!.getUserByUsername("Admin"), this) { user : User?->
            if (user != null) {
                handleSuccessLogin(user)
                observeOnce(
                    userViewmodel!!.getRule(user.id), this
                ) { rule: Rule? ->
                    if (rule != null) sessionManager!!.currentRule = rule
                }
            }
        }

//        observeOnce(userViewmodel?.allPermission!!, this,
//            Observer { permissions: MutableList<Permission> ->
//                sessionManager?.login(User(Const.SUPER_ADMIN_USERNAME, -1, Const.SUPER_ADMIN_PASSWORD, "0000"), permissions, -1)
//                observeOnce(
//                    userViewmodel!!.getRule(0), this
//                ) { rule: Rule? ->
//                    if (rule != null) sessionManager!!.currentRule = rule
//                }
//            }
//        )
    }
    private fun handleSuccessLogin(user : User) {
        userViewmodel!!.getUserRoles(user.id).observe(
            this
        ) { userRoles: Role ->
            userViewmodel!!.getRolePermissionName(userRoles.id).observe(
                this
            ) { permissions: MutableList<Permission> ->
                sessionManager?.currentRoleLevel = userRoles.level
                sessionManager!!.login(user, permissions, userRoles.id)
            }
        }
    }

    /**
     * 控制维护tab的显示/隐藏
     */
    fun showMaintenanceTab(show: Boolean) {
        bottomTab?.let { bottomNav ->
            val menu = bottomNav.menu
            val maintenanceItem = menu.findItem(R.id.menu_exit)

            if (show) {
                maintenanceItem.isVisible = true
                isMaintenanceTabVisible = true
            } else {
                maintenanceItem.isVisible = false
                isMaintenanceTabVisible = false

                // 如果当前选中的是维护tab，则切换到其他tab
                if (bottomNav.selectedItemId == R.id.menu_exit) {
                    bottomNav.selectedItemId = R.id.menu_mode
                }
            }
        }
    }


    private fun setupBottomNavigation() {
        val fragment = ModeFragment.newInstance("", "")
        val setFragment = SetFragment.newInstance()
        initView(fragment)

        bottomTab = binding.btmBar
        bottomTab?.setOnItemSelectedListener {
            when (it.itemId) {
                R.id.menu_mode -> {
                    // 切换到首页
                    initView(fragment)
                    true
                }

                R.id.menu_set -> {
                    // 跳转到设置
                    initView(setFragment)
                    true
                }

                R.id.menu_measure -> {
                    // 跳转到测量
                    initView(MeaFragment.newInstance())
                    true
                }

                R.id.msg_search -> {
                    // 跳转到查询
                    initView(SearchFragment.newInstance())
                    true
                }

                R.id.menu_exit -> {
                    // 跳转到维护
                    if (isMaintenanceTabVisible) {
                        initView(MaintenanceFragment.newInstance())
                        true
                    } else {
                        false
                    }
                }

                else -> false
            }
        }
    }

    //editView失去焦点的时候，将键盘关闭
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v: View? = currentFocus
            if (v is EditText) {
                val outRect = Rect()
                v.getGlobalVisibleRect(outRect)
                if (!outRect.contains(ev.rawX.toInt(), ev.rawY.toInt())) {
                    v.clearFocus()
                    val imm =
                        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
                    imm!!.hideSoftInputFromWindow(v.getWindowToken(), 0)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }



    private fun initView(fragment: Fragment) {
        val tag = fragment.javaClass.simpleName
        val existingFragment = supportFragmentManager.findFragmentByTag(tag)

        supportFragmentManager
            .beginTransaction()
            .replace(R.id.bot_tab, existingFragment ?: fragment, tag)
            .commit()

        // 创建事务 隐藏其他fragment页面，而不是替换
//        val transaction = supportFragmentManager.beginTransaction()

//        // 隐藏当前显示的 Fragment
//        currentFragment?.let {
//            if (!it.isHidden) {
//                transaction.hide(it)
//            }
//        }
//        // 查找目标 Fragment
//        val targetFragment = supportFragmentManager.findFragmentByTag(tag)
//
//        if (targetFragment == null) {
//            // 如果目标 Fragment 不存在，则添加它
//            transaction.add(R.id.bot_tab, fragment, tag)
//        } else {
//            // 如果目标 Fragment 存在，则显示它
//            if (targetFragment.isHidden) {
//                transaction.show(targetFragment)
//            }
//        }
//
//        transaction.commit()
//        currentFragment = targetFragment ?: fragment


    }
    private fun hideSystemBars() {
        val view = binding.root
        val window = (view.context as Activity).window

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 新 API 方式 (Android 11+)
            WindowCompat.setDecorFitsSystemWindows(window, false)
            window.insetsController?.let {
                it.hide(WindowInsets.Type.systemBars())
                it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE

            }
        } else {
            // 旧 API 方式 (Android 10 及以下)
            @Suppress("DEPRECATION")
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            or View.SYSTEM_UI_FLAG_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    )
        }
    }

    private fun registerBatteryReceiver() {
        batteryReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                val level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
                val status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1)

                // 判断是否充电
                val isCharging =
                    status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL

                Log.d("Battery", "电量：$level")
                // 根据是否充电更换图片
            }
        }
        registerReceiver(batteryReceiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
    }
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus) hideSystemBars()
    }
    override fun onDestroy() {
        super.onDestroy()
        statusBarManager?.stopUpdates()
    }

}